package com.ibeetl.cms.web;

import com.ibeetl.admin.console.service.DictConsoleService;
import com.ibeetl.admin.console.service.RoleConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.Message;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.MessageService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.*;
import com.ibeetl.cms.service.*;
import com.ibeetl.cms.util.BusinessTypeConstant;
import com.ibeetl.cms.util.ProcessConstant;
import com.ibeetl.cms.util.RoleConstant;
import com.ibeetl.cms.util.common;
import com.ibeetl.cms.web.quer3.IndustrialTalentsExamineQuery;
import com.ibeetl.cms.web.query.BuyHouseSubsidiesQuery;
import com.ibeetl.cms.web.query.IndustrialTalentsQuery;
import com.ibeetl.cms.web.query.IndustrialTalentsStrQuery;
import com.ibeetl.cms.web.query2.IndustrialTalentsEnterpriseQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.*;

/**
 * 产业人才
 */
@Controller
public class IndustrialTalentsController {

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/industrialTalents";


    @Autowired
    private IndustrialTalentsService industrialTalentsService;

    @Autowired
    FileService fileService;

    @Autowired
    CorePlatformService platformService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private EssentialInformationService essentialInformationService;

    @Autowired
    private BusinessProcessService businessProcessService;

    @Autowired
    private RoleConsoleService roleConsoleService;

    @Autowired
    private SincerityService sincerityService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private TelentCardService telentCardService;

    @Autowired
    private PretrialService pretrialService;

    @Autowired
    private DeclareLimitService declareLimitService;

    private StateTable stateTable = new StateTable();
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @ResponseBody
    public ModelAndView index(String roleName,String year,String entName) {
        ModelAndView view;
        if (roleName.equals("shenbao")) {
            view = new ModelAndView("/cms/industrialTalents/index.html");
            view.addObject("search", IndustrialTalentsQuery.class.getName());
        } else if (roleName.equals("shouli")) {
            view = new ModelAndView("/cms/industrialTalents/enterpriseindex.html");
            view.addObject("search", IndustrialTalentsEnterpriseQuery.class.getName());
        } else if (roleName.equals("chushen")) {
            view = new ModelAndView("/cms/industrialTalents/chushenindex.html");
            view.addObject("search", IndustrialTalentsExamineQuery.class.getName());
        } else {
            view = new ModelAndView("/cms/industrialTalents/fushenindex.html");
            view.addObject("search", IndustrialTalentsExamineQuery.class.getName());
        }

        if (roleName.equals("chushen") || roleName.equals("fushen")) {
            IndustrialTalentsQuery condtion = new IndustrialTalentsQuery();
            if(StringUtils.isNotEmpty(entName)){
                condtion.setEnterprisName(entName.trim());
            }
            view.addObject("entName",entName);
            if(StringUtils.isEmpty(year)){
                Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                year = yearNum.toString();
            }
            condtion.setYear(year.trim());
            view.addObject("year",year);

            /**
             * 获取本年度所有有申报的公司
             */
            List<IndustrialTalents> lists = industrialTalentsService.queryCompany(condtion);
            List<Map<String, Object>> companies = new ArrayList<>(16);

            for (IndustrialTalents industrialTalent : lists) {
                if(industrialTalent.getCompanyId() == null){
                    continue;
                }
                Map<String, Object> item = new HashMap<>(8);
                int  waitCheckNumber = 0;
                int  allCheckNumber = 0;
                if (roleName.equals("chushen")) {
                    waitCheckNumber = firstCheckNumber(Long.valueOf(industrialTalent.getCompanyId()), "TODO",year);
                    allCheckNumber = firstCheckNumber(Long.valueOf(industrialTalent.getCompanyId()), "ALL",year);
                }else{
                    waitCheckNumber = finalCheckNumber(Long.valueOf(industrialTalent.getCompanyId()), "TODO",year);
                    allCheckNumber = finalCheckNumber(Long.valueOf(industrialTalent.getCompanyId()), "ALL",year);
                }
                if(waitCheckNumber == 0){
                    //无待审核记录 不展示企业
                    continue;
                }
                item.put("companyId", industrialTalent.getCompanyId());
                item.put("companyName", industrialTalent.getCurrentWorkingEnterprise());
                item.put("waitCheckNumber", waitCheckNumber);
                item.put("allCheckNumber", allCheckNumber);
                companies.add(item);
            }
            view.addObject("companies", companies);

            view.addObject("roleName", roleName);
        }
        return view;
    }

    @PostMapping(MODEL + "/firstcheckList.json")
    @ResponseBody
    public JsonResult<PageQuery> firstcheckList(IndustrialTalentsQuery condtion) {
        /**
         * 获得本年度已办任务
         */
        if (condtion.getYear() == "" || condtion.getYear() == null) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        condtion.setProcessUserId(getUserId());
        condtion.setBusinessType(BusinessTypeConstant.industrialTalents);
        PageQuery page = condtion.getPageQuery();
        industrialTalentsService.queryDoneTask(page);
        return JsonResult.success(page);
    }

    /**
     * 初审获取该申报，该公司下的员工
     *
     * @param companyId
     * @return
     */
    @PostMapping(MODEL + "/employees.json")
    @Function("industrialTalents.check")
    @ResponseBody
    public JsonResult<PageQuery> employees(String companyId,String year) {
        IndustrialTalentsQuery condtion = new IndustrialTalentsQuery();
        condtion.setCompanyId(companyId);

        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condtion.setYear(year.trim());

        List<String> ids = new ArrayList();
        ids.add(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
        ids.add(ProcessConstant.FIRSTCHECK_STR);
        ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        ids.add(ProcessConstant.COMPANY_ADOPT_STR);
        ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        condtion.setIds(ids);

        PageQuery page = condtion.getPageQuery();
        industrialTalentsService.queryEmployees(page);
        return JsonResult.success(page);
    }

    /**
     * 复审获取该申报，该公司下的员工
     *
     * @param companyId
     * @return
     */
    @PostMapping(MODEL + "/fushenemployees.json")
    @Function("industrialTalents.review")
    @ResponseBody
    public JsonResult<PageQuery> fushenemployees(String companyId,String year) {
        IndustrialTalentsQuery condtion = new IndustrialTalentsQuery();
        condtion.setCompanyId(companyId);

        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condtion.setYear(year.trim());

        List<String> ids = new ArrayList();
        ids.add(ProcessConstant.FINALCHECK_TERMINIATE_STR);
        ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        ids.add(ProcessConstant.FINALCHECK_ADOPT_STR);
        ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        condtion.setIds(ids);

        PageQuery page = condtion.getPageQuery();
        industrialTalentsService.queryEmployees(page);
        return JsonResult.success(page);
    }

    @GetMapping(MODEL + "/shenhe.do")
    @ResponseBody
    public ModelAndView shenhe(Integer id, String roleName, String bStateCode) {
        ModelAndView view;
        if (bStateCode.equals(ProcessConstant.TO_FIRSTCHECK) && roleName.equals("chushen")) {
            view = new ModelAndView("/cms/industrialTalents/chushenedit.html");
        } else if (bStateCode.equals(ProcessConstant.TO_FINALCHECK) && roleName.equals("fushen")) {
            view = new ModelAndView("/cms/industrialTalents/fushenedit.html");
        } else {
            view = new ModelAndView("/cms/industrialTalents/findenterpriseedit.html");
            view.addObject("look", true);
        }

        IndustrialTalents industrialTalents = industrialTalentsService.queryById(id);
        Enterprise enterprise = enterpriseService.findenterprise(industrialTalents.getCompanyId());
        if(null != enterprise ) {
            industrialTalents.setDirectoryEnterprises(enterprise.getDirectoryEnterprises());
            if (enterprise.getBusinessQuota() == null) {
                industrialTalents.setBusinessQuota("0");
            } else {
                industrialTalents.setBusinessQuota(Integer.toString(enterprise.getBusinessQuota()));
            }
        }
        industrialTalents.setRoleName(roleName);
        view.addObject("industrialTalents", industrialTalents);
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("industrialTalents")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/industrialTalents/edit.html");
        IndustrialTalents industrialTalents = industrialTalentsService.queryById(id);
        view.addObject("industrialTalents", industrialTalents);
        Map<Integer, String> companies = new HashMap<>(16);
        for (int i = 1; i <= 12; i++) {
            companies.put(i, "" + i);
        }
        view.addObject("companies", companies);
        return view;
    }

    /**
     * 新增申报时的校验
     *
     * @return
     */
    @PostMapping(MODEL + "/addCheck.json")
    @Function("industrialTalents")
    @ResponseBody
    public JsonResult<Map<String, String>> addCheck() {
        Map<String, String> result = new HashMap<>(4);
        result.put("successFlag", "0");
        result.put("message", "industry talent card expire");
        return JsonResult.success(result);
    }

    @GetMapping(MODEL + "/add.do")
    @Function("industrialTalents")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/industrialTalents/add.html");
        Long userid = getUserId();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(userid);
        view.addObject("essentialInformation", essentialInformation);
        return view;
    }


    /**
     ** 功能描述:人才 - 个人申报记录获取
     ** @author liujun
     ** @date 2020/1/3 14:33
     **/
    @PostMapping(MODEL + "/list.json")
    @Function("industrialTalents")
    @ResponseBody
    public JsonResult<PageQuery> list(IndustrialTalentsQuery condtion) {
        Long userid = getUserId();
        condtion.setUserid(userid);
        if (StringUtils.isEmpty(condtion.getYear())) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        PageQuery page = condtion.getPageQuery();
        industrialTalentsService.queryByCondition(page);
        return JsonResult.success(page);
    }

    /**
     * 受理页面数据
     *
     * @param condtion
     * @return
     */
    @PostMapping(MODEL + "/Acceptancelist.json")
    @Function("industrialTalents.company")
    @ResponseBody
    public JsonResult<PageQuery> Acceptancelist(IndustrialTalentsQuery condtion) {
        condtion.setUserid(getUserId());
        if (condtion.getYear() == "" || condtion.getYear() == null) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        PageQuery page = condtion.getPageQuery();
        //查询用户对应的企业ID
        condtion.setCompanyId(getUserId().toString());
        if (condtion.getBusinessState() == "" || condtion.getBusinessState() == null) {
            condtion.setBusinessState(ProcessConstant.TO_COMPANY);
        } else {
            condtion.setBusinessState(condtion.getBusinessState());
        }
        //查询企业数据
        industrialTalentsService.findenterprise(page);
        return JsonResult.success(page);
    }
    @Autowired
    private DictConsoleService dictConsoleService;
    /**
     * 新增（保存）（保存并申请）
     *
     * @param industrialTalents
     * @return
     */
    @PostMapping(MODEL + "/add.json")
    @Function("industrialTalents")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class) IndustrialTalents industrialTalents, String judge) {
        CoreUser user = platformService.getCurrentUser();
        Long userId = getUserId();
        String yearStr = dictConsoleService.getDeclareYear();
        industrialTalents.setYear(yearStr);
        industrialTalents.setUserId(userId.intValue());
        industrialTalents.setCompanyId(Math.toIntExact(user.getCompanyId()));
        industrialTalents.setCreationDate(new Date());
        common.common(stateTable, judge);
        industrialTalents.setDateReporting(stateTable.getDate());
        industrialTalents.setBusinessState(stateTable.getBusinessState());
        industrialTalents.setBusinessStateCode(stateTable.getBusinessStateCode());
        industrialTalentsService.save(industrialTalents);
        //调用增加业务流程数据
        businessProcessService.processInformation(industrialTalents.getId(), stateTable.getBusinessState(), stateTable.getBusinessStateCode(), industrialTalents.getHandlingSuggestion(), "成功", BusinessTypeConstant.industrialTalents);
        return new JsonResult().success();
    }

    /**
     * 编辑（保存）（保存并申请）
     *
     * @param industrialTalents
     * @return
     */
    @PostMapping(MODEL + "/update.json")
    @Function("industrialTalents")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class) IndustrialTalents industrialTalents, String judge) {
        common.common(stateTable, judge);
        industrialTalents.setDateReporting(stateTable.getDate());
        industrialTalents.setBusinessState(stateTable.getBusinessState());
        industrialTalents.setBusinessStateCode(stateTable.getBusinessStateCode());
        boolean success = industrialTalentsService.updateTemplate(industrialTalents);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


    @GetMapping(MODEL + "/view.json")
    @Function("industrialTalents.company")
    @ResponseBody
    public JsonResult<IndustrialTalents> queryInfo(Integer id) {
        IndustrialTalents industrialTalents = industrialTalentsService.queryById(id);
        return JsonResult.success(industrialTalents);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("industrialTalents")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        industrialTalentsService.batchDelIndustrialTalents(idList);
        return new JsonResult().success();
    }

    /**
     * 查看页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/findenterprise.do")
    @ResponseBody
    public ModelAndView findenterprise(Integer id) {
        ModelAndView view = new ModelAndView("/cms/industrialTalents/findenterpriseedit.html");
        IndustrialTalents industrialTalents = industrialTalentsService.queryById(id);
        view.addObject("industrialTalents", industrialTalents);
        Map<Integer, String> companies = new HashMap<>(16);
        for (int i = 1; i <= 12; i++) {
            companies.put(i, i + "");
        }
        view.addObject("look", true);
        view.addObject("companies", companies);
        return view;
    }


    /**
     * 单位产业人才点击受理页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/acceptance.do")
    @Function("industrialTalents.company")
    @ResponseBody
    public ModelAndView acceptance(Integer id) {
        ModelAndView view = new ModelAndView("/cms/industrialTalents/acceptance.html");
        try {
            IndustrialTalents industrialTalents = industrialTalentsService.queryById(id);
            if (industrialTalents.getCompanyId() != null) {
                Enterprise enterprise = enterpriseService.findenterprise(industrialTalents.getCompanyId());
                industrialTalents.setDirectoryEnterprises(enterprise.getDirectoryEnterprises());
                if (enterprise.getBusinessQuota() == null) {
                    industrialTalents.setBusinessQuota("0");
                } else {
                    industrialTalents.setBusinessQuota(Integer.toString(enterprise.getBusinessQuota()));
                }
            }

            view.addObject("industrialTalents", industrialTalents);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }


    /**
     * 受理终止
     */
    @PostMapping(MODEL + "/Admissibility.json")
    @Function("industrialTalents.company")
    @ResponseBody
    public JsonResult<String> Admissibility(@Validated(ValidateConfig.UPDATE.class) IndustrialTalents industrialTalents) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("industrial_talents"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }

        industrialTalents.setBusinessState(ProcessConstant.TERMINIATE_STR);
        industrialTalents.setBusinessStateCode(ProcessConstant.TERMINIATE);
        industrialTalents.setProcessResult(ProcessConstant.COMPANY_TERMINIATE_STR);

        boolean postResult = pretrialService.post(AppInterfaceType.INDUSTRIAL_TALENTS_TYPE, industrialTalents.getExternalTaskId(), "2", "", "", industrialTalents.getHandlingSuggestion(), "0");

        if (postResult) {
            boolean success = industrialTalentsService.updateTemplate(industrialTalents);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(industrialTalents.getId(), industrialTalents.getBusinessState(), industrialTalents.getBusinessStateCode(), industrialTalents.getHandlingSuggestion(), ProcessConstant.COMPANY_TERMINIATE_STR, BusinessTypeConstant.industrialTalents);
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");
        }
    }

    /**
     * 受理退回
     */
    @PostMapping(MODEL + "/AdmissibleReturn.json")
    @Function("industrialTalents.company")
    @ResponseBody
    public JsonResult<String> AdmissibleReturn(@Validated(ValidateConfig.UPDATE.class) IndustrialTalents industrialTalents) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("industrial_talents"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }

        industrialTalents.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
        industrialTalents.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        industrialTalents.setProcessResult(ProcessConstant.COMPANY_BACK_STR);
        boolean postResult = pretrialService.post(AppInterfaceType.INDUSTRIAL_TALENTS_TYPE, industrialTalents.getExternalTaskId(), "1", "", "", industrialTalents.getHandlingSuggestion(), "1");

        if (postResult) {
            boolean success = industrialTalentsService.updateTemplate(industrialTalents);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(industrialTalents.getId(), ProcessConstant.COMPANY_BACK_STR, ProcessConstant.COMPANY_BACK, industrialTalents.getHandlingSuggestion(), ProcessConstant.COMPANY_BACK_STR, BusinessTypeConstant.industrialTalents);


                //给企业发一条退回信息
                Message message = new Message();
                message.setCompanyId(industrialTalents.getCompanyId());
                message.setUserId(industrialTalents.getUserId());
                message.setStatus(-1);
                message.setContent(industrialTalents.getHandlingSuggestion());
                message.setType(Integer.parseInt(BusinessTypeConstant.industrialTalents));
                message.setCreateDate(new Date());
                messageService.save(message);
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");

        }
    }

    /**
     * 受理通过
     */
    @PostMapping(MODEL + "/AcceptanceOK.json")
    @Function("industrialTalents.company")
    @ResponseBody
    public JsonResult<String> AcceptanceOK(@Validated(ValidateConfig.UPDATE.class) IndustrialTalents industrialTalents) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("industrial_talents"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }
        industrialTalents.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
        industrialTalents.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        industrialTalents.setProcessResult(ProcessConstant.COMPANY_ADOPT_STR);
        industrialTalents.setCompanyDeclareTime(new Date());
        /** 审批额度计算 **/
        BigDecimal TaxMonths = new BigDecimal(industrialTalents.getTaxMonths());
        //根据年薪 计算月薪 丢弃小数位 直接取整
        long subsidyNum = industrialTalents.getSalary().divide(TaxMonths, 0, BigDecimal.ROUND_DOWN).longValue();
        //上年度在名录内企业计税薪金纳税额
        BigDecimal salariesTax = industrialTalents.getSalariesTax();
        BigDecimal subsidy = new BigDecimal("0.00");
        if (subsidyNum >= 50000) {
            subsidy = salariesTax.multiply(new BigDecimal("0.2"));
        } else if (subsidyNum >= 18000 && subsidyNum < 50000) {
            subsidy = salariesTax.multiply(new BigDecimal("0.18"));
        } else {
            subsidy = salariesTax.multiply(new BigDecimal("0.15"));
        }
        boolean postResult = pretrialService.post(AppInterfaceType.INDUSTRIAL_TALENTS_TYPE, industrialTalents.getExternalTaskId(), "0", subsidy.toString(), "元", industrialTalents.getHandlingSuggestion(), "0");

        if (postResult) {
            boolean success = industrialTalentsService.updateTemplate(industrialTalents);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(industrialTalents.getId(), ProcessConstant.COMPANY_ADOPT_STR, ProcessConstant.COMPANY_ADOPT, industrialTalents.getHandlingSuggestion(), ProcessConstant.COMPANY_ADOPT_STR, BusinessTypeConstant.industrialTalents);
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");

        }

    }

    /**
     * 初审退回
     */
    @PostMapping(MODEL + "/initialReview.json")
    @Function("industrialTalents.check")
    @ResponseBody
    public JsonResult<String> initialReview(@Validated(ValidateConfig.UPDATE.class) IndustrialTalents industrialTalents) {
        industrialTalents.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
        industrialTalents.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        industrialTalents.setProcessResult(ProcessConstant.FIRSTCHECK_STR);
        //初审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        industrialTalents.setProcessUserId(currentUser.getId().intValue());
        industrialTalents.setProcessUserName(currentUser.getName());
        boolean success = industrialTalentsService.updateTemplate(industrialTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(industrialTalents.getId(), ProcessConstant.FIRSTCHECK_STR, ProcessConstant.FIRSTCHECK, industrialTalents.getHandlingSuggestion(), ProcessConstant.FIRSTCHECK_STR, BusinessTypeConstant.industrialTalents);
            //给企业发一条退回信息
            Message message = new Message();
            message.setCompanyId(industrialTalents.getCompanyId());
            message.setUserId(industrialTalents.getUserId());
            message.setStatus(-1);
            message.setContent(industrialTalents.getHandlingSuggestion());
            message.setType(Integer.parseInt(BusinessTypeConstant.industrialTalents));
            message.setCreateDate(new Date());
            messageService.save(message);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 复审退回
     */
    @PostMapping(MODEL + "/Reexamination.json")
    @Function("industrialTalents.review")
    @ResponseBody
    public JsonResult<String> Reexamination(@Validated(ValidateConfig.UPDATE.class) IndustrialTalents industrialTalents) {
        industrialTalents.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
        industrialTalents.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        industrialTalents.setProcessResult(ProcessConstant.FINALCHECK_BACK_STR);
        //复审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        industrialTalents.setReviewUserId(currentUser.getId().intValue());
        industrialTalents.setReviewUserName(currentUser.getName());
        boolean success = industrialTalentsService.updateTemplate(industrialTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(industrialTalents.getId(), ProcessConstant.FINALCHECK_BACK_STR, ProcessConstant.FINALCHECK_BACK, industrialTalents.getHandlingSuggestion(), ProcessConstant.FINALCHECK_BACK_STR, BusinessTypeConstant.industrialTalents);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 初审通过
     */
    @PostMapping(MODEL + "/FirstTrial.json")
    @Function("industrialTalents.check")
    @ResponseBody
    public JsonResult<String> FirstTrial(@Validated(ValidateConfig.UPDATE.class) IndustrialTalents industrialTalents) {
        String businessType = "1";
        if (industrialTalents.getRoleName().equals("chushen")) {
            List<Sincerity> sincerityList = sincerityService.blacklist(industrialTalents.getUserId(), industrialTalents.getCompanyId(), businessType);
            if (null != sincerityList && sincerityList.size() > 0) {
                //用户或用户所属企业已进入黑名单
                for (Sincerity sincerity : sincerityList) {
                    if (sincerity.getType().equals(Long.toString(RoleConstant.PERSON))) {
                        //个人
                        return JsonResult.failMessage(industrialTalents.getName() + "在黑名单中有记录");
                    } else if (sincerity.getType().equals(Long.toString(RoleConstant.COMPANY))) {
                        //企业
                        String name = enterpriseService.findenterprise(industrialTalents.getCompanyId()).getEnterpriseName();
                        return JsonResult.failMessage(name + "公司在黑名单中有记录");
                    }
                }
            }
        }
        industrialTalents.setBusinessState(ProcessConstant.TO_FINALCHECK_STR);
        industrialTalents.setBusinessStateCode(ProcessConstant.TO_FINALCHECK);
        industrialTalents.setProcessResult(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        //初审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        industrialTalents.setProcessUserId(currentUser.getId().intValue());
        industrialTalents.setProcessUserName(currentUser.getName());
        boolean success = industrialTalentsService.updateTemplate(industrialTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(industrialTalents.getId(), ProcessConstant.FIRSTCHECK_ADOPT_STR, ProcessConstant.FIRSTCHECK_ADOPT, industrialTalents.getHandlingSuggestion(), ProcessConstant.FIRSTCHECK_ADOPT_STR, BusinessTypeConstant.industrialTalents);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 复审通过
     */
    @PostMapping(MODEL + "/ReviewThrough.json")
    @Function("industrialTalents.review")
    @ResponseBody
    public JsonResult<String> ReviewThrough(@Validated(ValidateConfig.UPDATE.class) IndustrialTalents industrialTalents) {
        industrialTalents.setBusinessState(ProcessConstant.DONE_STR);
        industrialTalents.setBusinessStateCode(ProcessConstant.DONE);
        industrialTalents.setProcessResult(ProcessConstant.FINALCHECK_ADOPT_STR);
        //复审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        industrialTalents.setReviewUserId(currentUser.getId().intValue());
        industrialTalents.setReviewUserName(currentUser.getName());
        boolean success = industrialTalentsService.updateTemplate(industrialTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(industrialTalents.getId(), ProcessConstant.FINALCHECK_ADOPT_STR, ProcessConstant.FINALCHECK_ADOPT, industrialTalents.getHandlingSuggestion(), ProcessConstant.FINALCHECK_ADOPT_STR, BusinessTypeConstant.industrialTalents);

            //新业务要求：人才卡需待公示后统一生成 20200225
            //生成产业人才卡
            //telentCardService.generateCard(industrialTalents.getUserId(), industrialTalents.getSalary(), industrialTalents.getTaxMonths(), industrialTalents.getName(), industrialTalents.getSex(), industrialTalents.getIdentificationNumber());

            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }
    /**
     * 初审终止
     */
    @PostMapping(MODEL + "/FirstTrialTermination.json")
    @Function("industrialTalents.check")
    @ResponseBody
    public JsonResult<String> FirstTrialTermination(@Validated(ValidateConfig.UPDATE.class) IndustrialTalents industrialTalents) {
        industrialTalents.setBusinessState(ProcessConstant.TERMINIATE_STR);
        industrialTalents.setBusinessStateCode(ProcessConstant.TERMINIATE);
        industrialTalents.setProcessResult(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
        //初审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        industrialTalents.setProcessUserId(currentUser.getId().intValue());
        industrialTalents.setProcessUserName(currentUser.getName());
        boolean success = industrialTalentsService.updateTemplate(industrialTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(industrialTalents.getId(), industrialTalents.getBusinessState(), industrialTalents.getBusinessStateCode(), industrialTalents.getHandlingSuggestion(), ProcessConstant.FIRSTCHECK_TERMINIATE_STR, BusinessTypeConstant.industrialTalents);

            //给企业发一条终止信息
            Message message = new Message();
            message.setCompanyId(industrialTalents.getCompanyId());
            message.setUserId(industrialTalents.getUserId());
            message.setStatus(-1);
            message.setContent(industrialTalents.getHandlingSuggestion());
            message.setType(Integer.parseInt(BusinessTypeConstant.industrialTalents));
            message.setCreateDate(new Date());
            messageService.save(message);

            return JsonResult.success();
        } else {
            return JsonResult.failMessage("保存失败");
        }

    }

    /**
     * 复审终止
     */
    @PostMapping(MODEL + "/RetrialTermination.json")
    @Function("industrialTalents.review")
    @ResponseBody
    public JsonResult<String> RetrialTermination(@Validated(ValidateConfig.UPDATE.class) IndustrialTalents industrialTalents) {
        industrialTalents.setBusinessState(ProcessConstant.TERMINIATE_STR);
        industrialTalents.setBusinessStateCode(ProcessConstant.TERMINIATE);
        industrialTalents.setProcessResult(ProcessConstant.FINALCHECK_TERMINIATE_STR);
        //复审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        industrialTalents.setReviewUserId(currentUser.getId().intValue());
        industrialTalents.setReviewUserName(currentUser.getName());
        boolean success = industrialTalentsService.updateTemplate(industrialTalents);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(industrialTalents.getId(), industrialTalents.getBusinessState(), industrialTalents.getBusinessStateCode(), industrialTalents.getHandlingSuggestion(), ProcessConstant.FINALCHECK_TERMINIATE_STR, BusinessTypeConstant.industrialTalents);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    @PostMapping(MODEL + "/batchFinalCheckPass.json")
    @Function("industrialTalents.review")
    @ResponseBody
    public JsonResult<String> batchFinalCheckPass(String ids,String year) {
        /**
         * 更改状态为生效
         */
        List<Long> idList = ConvertUtil.str2longs(ids);
        for (Long id : idList) {
            /**
             * 获得这个公司id下所有待复审的业务
             */
            BuyHouseSubsidiesQuery condtion = new BuyHouseSubsidiesQuery();

            if(StringUtils.isEmpty(year)) {
                Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                year = yearNum.toString();
            }
            condtion.setYear(year.trim());
            condtion.setCompanyId(id);

            List<String> params = new ArrayList();
            params.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
            condtion.setIds(params);
            PageQuery page = condtion.getPageQuery();
            page.setPageSize(Integer.MAX_VALUE);
            industrialTalentsService.queryEmployees(page);
            List<IndustrialTalents> industrialTalentsList = page.getList();

            for (IndustrialTalents industrialTalents : industrialTalentsList) {
                industrialTalents.setBusinessState(ProcessConstant.DONE_STR);
                industrialTalents.setBusinessStateCode(ProcessConstant.DONE);
                industrialTalents.setProcessResult(ProcessConstant.FINALCHECK_ADOPT_STR);
                //复审人和id
                CoreUser currentUser = platformService.getCurrentUser();
                industrialTalents.setReviewUserId(currentUser.getId().intValue());
                industrialTalents.setReviewUserName(currentUser.getName());
                boolean success = industrialTalentsService.updateTemplate(industrialTalents);
                if (success) {
                    //调用增加业务流程数据
                    businessProcessService.processInformation(industrialTalents.getId(), ProcessConstant.FINALCHECK_ADOPT_STR, ProcessConstant.FINALCHECK_ADOPT, industrialTalents.getHandlingSuggestion(), ProcessConstant.FINALCHECK_ADOPT_STR, BusinessTypeConstant.industrialTalents);

                    //生成产业人才卡
                   //  telentCardService.generateCard(industrialTalents.getUserId(), industrialTalents.getSalary(), industrialTalents.getTaxMonths(), industrialTalents.getName(), industrialTalents.getSex(), industrialTalents.getIdentificationNumber());

                }
            }
        }
        return JsonResult.success();

    }

// 人才公共方法(所有)

    /**
     * 公共方法
     * 用于获取登录ID
     *
     * @return
     */
    public Long getUserId() {
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        return userId;
    }


    /**
     * 获取初审的数量
     */
    private int firstCheckNumber(Long companyId, String type,String year) {
        /**
         * 获取待初审的数量,type = 'TODO'
         */
        IndustrialTalentsQuery condition = new IndustrialTalentsQuery();

        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condition.setYear(year.trim());
        condition.setCompanyId(String.valueOf(companyId));

        List<String> ids = new ArrayList();
        if ("TODO".equalsIgnoreCase(type)) {
            ids.add(ProcessConstant.COMPANY_ADOPT_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        } else {
            ids.add(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
            ids.add(ProcessConstant.FIRSTCHECK_STR);
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
            ids.add(ProcessConstant.COMPANY_ADOPT_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        }

        condition.setIds(ids);
        int size = 0 ;
        try{
            size = industrialTalentsService.queryEmployeesCount(condition);
        }catch (Exception e){
            log.error("数据查询异常，异常消息:"+e.getMessage());
        }
        return size;
    }

    /**
     * 获取复审的数量
     */
    private int finalCheckNumber(Long companyId, String type,String year) {
        /**
         * 获取待初审的数量,type = 'TODO'
         */

        IndustrialTalentsQuery condition = new IndustrialTalentsQuery();

        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condition.setYear(year.trim());
        condition.setCompanyId(String.valueOf(companyId));

        List<String> ids = new ArrayList();
        if ("TODO".equalsIgnoreCase(type)) {
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        } else {
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);

            ids.add(ProcessConstant.FINALCHECK_TERMINIATE_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
            ids.add(ProcessConstant.FINALCHECK_ADOPT_STR);
        }

        condition.setIds(ids);
        int size = 0 ;
        try{
            size = industrialTalentsService.queryEmployeesCount(condition);
        }catch (Exception e){
            log.error("数据查询异常，异常消息:"+e.getMessage());
        }
        return size;
    }

    /**
     * 人才卡生产功能页面跳转
     * @return
     */
    @GetMapping(MODEL + "/indexStr.do")
    @Function("cms.industrialTalentsStr")
    @ResponseBody
    public ModelAndView indexStr() {
        ModelAndView view;
        view = new ModelAndView("/cms/industrialTalents/indexStr.html");
        view.addObject("search", IndustrialTalentsStrQuery.class.getName());
        return view;
    }

    /**
     * 查询本年度所有已生效的人才数据
     * @param condtion
     * @return
     */
    @PostMapping(MODEL + "/listStr.json")
    @Function("cms.industrialTalentsStr")
    @ResponseBody
    public JsonResult<PageQuery> listStr(IndustrialTalentsStrQuery condtion) {
        if (condtion.getYear() == "" || condtion.getYear() == null) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        condtion.setBusinessStateCode(ProcessConstant.DONE);
        PageQuery page = condtion.getPageQuery();
        industrialTalentsService.queryByCondition(page);
        return JsonResult.success(page);
    }

    /**
     * 批量生产人才卡功能
     * @param ids
     * @return
     */
    @PostMapping(MODEL + "/volumeProduction.json")
    //@Function("industrialTalents")
    @ResponseBody
    public JsonResult volumeProduction(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        List<IndustrialTalents> list=industrialTalentsService.findIndustrial(idList);
        int i=0;
        for (IndustrialTalents industrialTalents :list){
            //生成产业人才卡
           telentCardService.generateCard(industrialTalents.getSalary(), industrialTalents.getTaxMonths(), industrialTalents.getName(), industrialTalents.getSex(), industrialTalents.getIdentificationNumber(),industrialTalents.getSocialCreditCode());
           log.info("人才卡批量生成业务:userId=["+industrialTalents.getUserId()+"],业务id:["+industrialTalents.getId()+"]");
           i++;
        }
        log.info("本次共操作数据记录["+i+"]条");
        return new JsonResult().success();
    }

    /**
     * 一键批量生产人才卡功能
     * 超级管理员单独操作功能
     * @return
     */
    @GetMapping(MODEL + "/volumeProduction_admin.json")
    //@Function("industrialTalents")
    @ResponseBody
    public JsonResult volumeProductionAdmin() {
        CoreUser currentUser = platformService.getCurrentUser();
        if(currentUser == null || !"superadmin".equals(currentUser.getCode())){
            return JsonResult.failMessage("权限不足");
        }
        IndustrialTalentsStrQuery condtion = new IndustrialTalentsStrQuery();
        condtion.setYear("2020");
        condtion.setBusinessStateCode(ProcessConstant.DONE);
        PageQuery page = condtion.getPageQuery();
        page.setPageSize(99999999);
        List<IndustrialTalents> list=industrialTalentsService.queryByCondition(page).getList();
        int i=0;
        for (IndustrialTalents industrialTalents :list){
            //生成产业人才卡
            telentCardService.generateCard(industrialTalents.getSalary(), industrialTalents.getTaxMonths(), industrialTalents.getName(), industrialTalents.getSex(), industrialTalents.getIdentificationNumber(),industrialTalents.getSocialCreditCode());
            log.info("人才卡批量生成业务:userId=["+industrialTalents.getUserId()+"],业务id:["+industrialTalents.getId()+"]");
            i++;
        }
        log.info("本次共操作数据记录["+i+"]条");
        return new JsonResult().success();
    }

}
